<template>
	<view class="img_list">
		<view class="img" :style="{width:`${width || 180}rpx;`,height:`${height || 180}rpx;`}" v-for='(item, index) in list'>
			<image class="item" :src="item" mode="aspectFill"></image>
			<view class='del cuIcon-roundclosefill' @click='delImg(index)' v-if="!isLook"></view>
		</view>
		<view class="up-box" @click='addImg'>
			<slot name="upBox"></slot>
		</view>
	</view>
</template>

<script>
	import { imgUpload } from '@/api/common'
	export default {
		props:{
			value: String, //图片列表
			// 多图片拼接符号
			joinStr: {
				type: String,
				default: '@'
			},
			isLook:{
				type: Boolean,
				default: false
			},
			// 最大上传数量
			limit: {
				type: Number,
				default: 5
			},
			width:[String,Number],
			height:[String,Number],
		},
		data() {
			return {
				// 图片列表
				list: []
			}
		},
		watch: {
			value(val) {
				this.formatList(val)
			}
		},
		created() {
			this.formatList(this.value)
		},
		methods: {
			// 新增图片
			addImg() {
				if(this.list.length == this.limit) {
					uni.showToast({title: '超出最大上传限制', icon: 'none'})
					return;
				}
				uni.chooseImage({
					count: 1,
					success: res => {
						let tempFilePaths = res.tempFilePaths[0];
						this.upload(tempFilePaths)
					}
				})
			},
			upload(file) {
				imgUpload(file).then(res => {
					let data = JSON.parse(res.data);
					this.list.push(data.url)
					this.$emit('input', this.list.join(this.joinStr))
					this.$emit('change', this.list)
				})
				
			},
			delImg(index){
				this.list.splice(index, 1);
				this.$emit('input', this.list.join(this.joinStr))
				this.$emit('change', this.list)
			},
			// 格式化图片列表
			formatList(val) {
				if(val != '') {
					this.list = val.split(this.joinStr)
				} else {
					this.list = []
				}
			}
		}
	}
</script>

<style lang="scss" scoped>

	.img_list{
		width: 100%;
		display: flex;
		flex-flow: row wrap;
		.img{
			width: 180rpx;
			height: 180rpx;
			border-radius: 8rpx;
			position: relative;
			margin-right: 20rpx;
			margin-bottom: 20rpx;
			.item{
				width: 100%;
				height: 100%;
				border-radius: 4rpx;
			}
			.del{
				position: absolute;
				font-size: 32rpx;
				top: -12rpx;
				right: -12rpx;
			}
		}
		.add{
			width: 200rpx;
			height: 200rpx;
			border-radius: 8rpx;
		}
	}
</style>